<script lang="ts" setup>
interface Props {
  startTime?: number
  endTime: number
  isShow?: boolean
}
// 定义默认的Props值
const props = withDefaults(defineProps<Props>(), {
  startTime: Date.now(),
  endTime: Date.now() + 1000 * 60 * 60 * 24,
  isShow: true,
})
const emit = defineEmits<{
  (e: 'end'): void
}>()
const { startTime, endTime } = toRefs(props)

// 创建响应式数据remainingTime，表示剩余时间
const remainingTime = ref(endTime.value - startTime.value)

// 定义用于格式化时间的函数
const formatTimeText = (time: number): string => {
  return time < 10 ? `0${time}` : `${time}`
}

// 定义更新remainingTime的函数
const updateTime = (props: Props) => {
  remainingTime.value = props.endTime - Date.now()
}
const intervalId = ref<number | null>(null)

// 监听props的变化，每秒钟更新一次remainingTime
watchEffect(() => {
  if (props.isShow) {
    if (remainingTime.value > 0) {
      updateTime(props)
      intervalId.value = setInterval(() => {
        updateTime(props)
      }, 1000)
    }
    else {
      clearInterval(intervalId.value as number)
      emit('end')
    }
  }
  else {
    clearInterval(intervalId.value as number)
  }
})
// 利用computed函数计算倒计时文本
const timeText = computed(() => {
  const hours = Math.floor((remainingTime.value / 1000 / 60 / 60))
  const minutes = Math.floor((remainingTime.value / 1000 / 60) % 60)
  const seconds = Math.floor((remainingTime.value / 1000) % 60)

  return `${formatTimeText(hours)}:${formatTimeText(minutes)}:${formatTimeText(seconds)}`
})

onUnmounted(() => {
  clearInterval(intervalId.value as number)
})
</script>

<template>
  {{ timeText }}
</template>
